﻿// ***********************************************************************
// 程 序 集  : HdhNetQuery
// 建立时间  : 2025-09
// 类库说明  ：通用函数操作类
// 个人网站  ：http://www.hdhcms.com 
// ***********************************************************************
// <copyright>
//     Copyright by He DongHua(何冬华) All, QQ群:876705805 QQ:664627440 Email:664627440@qq.com
// </copyright>
// 如果要使用当前代码，请保存这些信息
// ***********************************************************************
using Microsoft.Extensions.Configuration;
using System.Data;
using System.Text.RegularExpressions;

namespace HdhNetQuery
{
    public static class HdhcmsUniversalFunction
    {
        public static int GetDataType()
        {
            //核心依赖包
            //需要安装以下三个关键NuGet包才能使用SetBasePath方法：
            //Microsoft.Extensions.Configuration - 提供配置系统基础功能
            //Microsoft.Extensions.Configuration.FileExtensions - 包含文件相关的配置扩展方法
            //Microsoft.Extensions.Configuration.Json - 支持JSON文件配置读取 
            var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            int hdhBack = 0;//默认返回Sqlite类型
            try
            {
                hdhBack = Convert.ToInt16(configuration["ConnectionStrings:hdhDataType"]);
            }
            catch { }
            return hdhBack;
        }

        #region 数字、日期、字符转换方法
        public static int ToInt(object i)
        {
            int rst = 0;
            //int.TryParse(i.ToString(), out rst);
            try
            {
                rst = Convert.ToInt32(i);
            }
            catch { rst = 0; }
            return rst;
        }
        public static decimal ToDecimal(object i)
        {
            decimal rst = 0;
            try
            {
                decimal.TryParse(i.ToString(), out rst);
            }
            catch { rst = 0; }
            return rst;
        }
        public static double ToDouble(object i)
        {
            double rst = 0;
            double.TryParse(i.ToString(), out rst);
            return rst;
        }
        public static string ToDate(object i)
        {
            DateTime rst = DateTime.Parse("1970-01-01");
            DateTime.TryParse(i.ToString(), out rst);
            return rst.ToString("yyyy-MM-dd");
        }
        public static string ToDateTime(object i)
        {
            DateTime rst = DateTime.Parse("1970-01-01");
            DateTime.TryParse(i.ToString(), out rst);
            return rst.ToString("yyyy-MM-dd HH:ss:mm");
        }


        #endregion
        #region 数字逻辑判断操作函数
        /// <summary>
        /// 判断是否为数字
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool IsNum(object value)
        {
            int number;
            return int.TryParse(value.ToString(), out number);
        }
        /// <summary>
        /// 判断是否为数字，不限制数字的类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsNumericType(object obj)
        {
            if (obj == null) return false;
            Type type = obj.GetType();
            return type == typeof(byte) || type == typeof(sbyte)
                || type == typeof(short) || type == typeof(ushort)
                || type == typeof(int) || type == typeof(uint)
                || type == typeof(long) || type == typeof(ulong)
                || type == typeof(float) || type == typeof(double)
                || type == typeof(decimal);
        }
        #endregion
        #region 邮件电话检测判断函数
        /// <summary>
        /// 验证邮箱
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public static bool IsValidEmail(string email)
        {
            // 定义电子邮件地址的正则表达式模式
            string pattern = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
            // 使用正则表达式匹配电子邮件地址
            Regex regex = new Regex(pattern);
            return regex.IsMatch(email);
        }
        /// <summary>
        /// 验证电话号码号
        /// </summary>
        /// <param name="telNumber"></param>
        /// <returns></returns>
        public static bool IsValidTelNumber(string telNumber)
        {
            // 定义电话号码的正则表达式模式
            string pattern = @"^\d{3}-\d{3}-\d{4}$";
            // 使用正则表达式匹配电话号码
            Regex regex = new Regex(pattern);
            return regex.IsMatch(telNumber);
        }
        /// <summary>
        /// 验证手机号
        /// </summary>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public static bool IsValidPhoneNumber(string phoneNumber)
        {
            // 定义手机号码的正则表达式模式
            string pattern = @"^1[3456789]\d{9}$";

            // 使用正则表达式匹配手机号码
            Regex regex = new Regex(pattern);
            return regex.IsMatch(phoneNumber);
        }
        #endregion

        #region 数字、字符、日期、文件处理函数
        /// <summary>
        /// 尾0清除
        /// </summary>
        public static decimal MoveZero(string str)
        {
            decimal number = decimal.Parse(str);
            string formattedNumber = Math.Round(number, 0).ToString();
            return decimal.Parse(formattedNumber);
        }
        /// <summary>
        /// 正则表达式获取字符串中指定的符号序列
        /// </summary>
        /// <param name="strInput"></param>
        /// <param name="strSymbols"></param>
        /// <returns></returns>
        public static string RegexGetStringSymbols(string strInput, string strSymbols)
        {
            //string strInput = "a&b|c|d&e";
            //string strSymbols = "[&|]";
            // 正则表达式：匹配 & 或 |
            Regex regex = new Regex(strSymbols);
            // 获取所有匹配的符号
            MatchCollection matches = regex.Matches(strInput);
            // 提取符号并按顺序排列
            var symbols = matches.Cast<Match>()
                                .Select(m => m.Value)
                                .ToList();
            // 输出结果
            //Console.WriteLine("提取的符号: " + string.Join(", ", symbols));
            string strBack = string.Join(",", symbols);
            return strBack;
        }
        /// <summary>
        /// 处理SQL查询中的字符
        /// </summary>
        /// <param name="strDo"></param>
        /// <returns></returns>
        public static string SqlReplaceString(string strDo)
        {
            //关键词
            string[] strBadChar =
        {
            "and"
            ,"exec"
            ,"insert"
            ,"select"
            ,"delete"
            ,"update"
            ,"count"
            ,"from"
            ,"drop"
            ,"asc"
            ,"char"
            ,"or"
            ,"%"
            ,";"
            ,":"
            ,"'"
            ,"-"
            ,"chr"
            ,"mid"
            ,"master"
            ,"truncate"
            ,"char"
            ,"declare"
            ,"SiteName"
            ,"net user"
            ,"xp_cmdshell"
            ,"/add"
            ,"exec master.dbo.xp_cmdshell"
            ,"net localgroup administrators"
        };
            strDo = strDo.Replace("'", "''").Replace("--", "").Replace("%", "");
            while (strDo.IndexOf("--") > -1)
            {
                strDo = strDo.Replace("--", "");
            }
            return strDo;
        }
        /// <summary>
        /// 截取字符串长度
        /// </summary>
        /// <param name="str">被截取的字符串</param>
        /// <param name="strSubstringLength">要截取的长度</param>
        /// <param name="strStart">截到的位置,从0开始</param>
        /// <returns></returns>
        public static string Substring(string str, int strSubstringLength, int strStart = 0)
        {
            int allStringLength = str.Length;
            try
            {
                if (allStringLength <= strStart)
                {
                    //无字符串可截取
                    str = "";
                }
                else
                {
                    //可截取字符串数量
                    int canSubstringCount = allStringLength - (strStart + 1);
                    if (canSubstringCount > 0)
                    {
                        if (canSubstringCount > strSubstringLength)
                        {
                            str = str.Substring(strStart, strSubstringLength);
                        }
                        else
                        {
                            str = str.Substring(strStart);
                        }
                    }
                    else
                    {
                        //无字符串可截取
                        str = "";
                    }
                }
            }
            catch
            {
                str = "";
            }
            return str;
        }
        /// <summary>
        /// 数字生成指定长度字符串不足前面补指定字符
        /// </summary>
        /// <param name="length">生成字符串的总长度</param>
        /// <param name="digit">生成字符串的数字</param>
        /// <param name="prechar">前面要被的字符</param>
        /// <returns></returns>
        public static string GetLenthStrByNumPreZero(int length, int digit, char prechar = '0')
        {
            string strDig = (digit + 1).ToString();
            string reBack = strDig;
            if (length - strDig.Length > 0)
            {
                reBack = (new string('0', length - strDig.Length)) + strDig;
            }
            return reBack;//C#用String生成重复的字符
        }

        #endregion
        #region 文件处理函数
        /// <summary>
        /// 新增DB文件
        /// </summary>
        /// <param name="strFileName"></param>
        public static void CreateFile(string strFileName)
        {
            string dbFile = Directory.GetCurrentDirectory() + strFileName; // 指定数据库文件路径
            string dbPath = dbFile.Substring(0, dbFile.LastIndexOf("\\"));
            if (!Directory.Exists(dbPath))
            {
                Directory.CreateDirectory(dbPath);
            }
            if (!File.Exists(dbFile))
            {
                File.Create(dbFile); // 创建新的SQLite数据库文件
            }
        }

        #endregion
    }
}
